/*
    Copyright 2011 Anishek Agarwal(anishek@gmail.com), Ashish Mishra(ashish@ashishmishra.in)
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.thoughtworks.ant;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Properties {
    private Store<String, File> propertyKeys = new Store<String, File>();
    private Store<String, PropertyLocator> propertyValueLocators = new Store<String, PropertyLocator>();

    public Properties(Set<File> bundleFiles) {
        for (File file : bundleFiles) {
            scan(file);
        }
    }

    private void scan(File file) {
        if (file.exists()) {
            try {
                java.util.Properties properties = new java.util.Properties();
                properties.load(new FileReader(file));
                for (String key : properties.stringPropertyNames()) {
                    propertyKeys.put(key, file);
                    propertyValueLocators.put(properties.getProperty(key), new PropertyLocator(key, file));
                }
            } catch (IOException e) {
                System.out.println("Could not Scan property file : " + file.getAbsolutePath());
            }
        }
    }

    private <T> Store<String, T> duplicates(Store<String, T> store) {
        Store<String, T> duplicates = new Store<String, T>();
        for (String value : store.keySet()) {
            if (store.hasDuplicates(value)) {
                duplicates.putAll(value, store.get(value));
            }
        }
        return duplicates;
    }

    public Store<String, PropertyLocator> keysWithSameValues() {
        return duplicates(propertyValueLocators);
    }

    public Store<String, File> duplicateKeyDeclarations() {
        return duplicates(propertyKeys);
    }

    public List<String> unused(Set<File> sourceFiles) {
        List<String> unusedProperties = new ArrayList<String>(propertyKeys.keySet());
        for (File file : sourceFiles) {
            findUsage(new Source(file), unusedProperties);
        }
        return unusedProperties;
    }

    private void findUsage(Source source, List<String> unusedProperites) {
        ListIterator<String> listIterator = unusedProperites.listIterator();
        while (listIterator.hasNext()) {
            if (source.contains(listIterator.next()))
                listIterator.remove();
        }
    }
}
